package com.cumt.threeway.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cumt.threeway.R;
import com.cumt.threeway.constant.ThreeWayConstant;
import com.cumt.threeway.constant.URLS;
import com.cumt.threeway.fragment.AbstractFragment;
import com.cumt.threeway.fragment.CommentFragment;
import com.cumt.threeway.fragment.ContentFragment;
import com.cumt.threeway.model.Single;
import com.cumt.threeway.util.ThreeWayUtil;
import com.cumt.threeway.view.dialog.NeedLoginDialog;
import com.cumt.threeway.view.widget.SelectPicPopupWindow;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 胡晶晶 on 2016/5/22.
 */
public class SubmitActivity extends FragmentActivity implements View.OnClickListener{

    private ImageView mIvIco;
    private ImageView mIvFavourite;
    private TextView mNameTextView;
    private TextView mDateTextView;
    private TextView mAbstractTextView;
    private TextView mContentTextView;
    private TextView mCommentTextView;
    private Single mSingle;
    private ThreeWayConstant.FRAGMENT_TYPE mFragmentType= ThreeWayConstant.FRAGMENT_TYPE.UN_KNOE;
    private AbstractFragment mAbstractFragment;
    private ContentFragment mContentFragment;
    private CommentFragment mCommentFragment;
    private FragmentManager mFragmentManager;
    SelectPicPopupWindow menuWindow;
    private RequestQueue queue;
    private boolean isFavourite = false;//true 收藏 false 未收藏

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify_baoming);
        mFragmentManager = getSupportFragmentManager();
        if(savedInstanceState != null) {
            mAbstractFragment = (AbstractFragment) mFragmentManager.findFragmentByTag("AbstractFragment");
            mContentFragment = (ContentFragment) mFragmentManager.findFragmentByTag("ContentFragment");
            mCommentFragment = (CommentFragment) mFragmentManager.findFragmentByTag("CommentFragment");
        }
//        mAbstractFragment = new AbstractFragment();
//        mContentFragment = new ContentFragment();
//        mCommentFragment = new CommentFragment();
        initView();
        initData();
    }

    private void initView() {
        queue = Volley.newRequestQueue(this);
        mIvFavourite = (ImageView) findViewById(R.id.iv_favourite);
        mIvIco = (ImageView) findViewById(R.id.iv_tupian);
        mNameTextView = (TextView) findViewById(R.id.tv_sign_up_name);
        mDateTextView = (TextView) findViewById(R.id.tv_sign_up_date);
        mAbstractTextView = (TextView) findViewById(R.id.tv_gaiyao);
        mContentTextView = (TextView) findViewById(R.id.tv_xiangqing);
        mCommentTextView = (TextView) findViewById(R.id.tv_pingjia);
        findViewById(R.id.btn_back).setOnClickListener(this);
        findViewById(R.id.yello_layout).setOnClickListener(this);
        findViewById(R.id.red_layout).setOnClickListener(this);
        if("notShowFavourite".equals(getIntent().getStringExtra("notShowFavourite"))){
            mIvFavourite.setVisibility(View.GONE);
        }

        mAbstractTextView.setOnClickListener(this);
        mContentTextView.setOnClickListener(this);
        mCommentTextView.setOnClickListener(this);
        mIvFavourite.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        mSingle = (Single) intent.getSerializableExtra("single");
        if(!TextUtils.isEmpty(mSingle.getFlag())) {
            mIvFavourite.setImageResource(R.drawable.rating_star_green);
            isFavourite = true;
        }
        ImageLoader.getInstance().displayImage(mSingle.getAimage(), mIvIco);
        mNameTextView.setText(mSingle.getAname());
        mDateTextView.setText(mSingle.getDate());
        mFragmentType = ThreeWayConstant.FRAGMENT_TYPE.ABSTRACT;
        setTabSelection();
    }

    public void setTabSelection() {
        clearSelection();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (mFragmentType) {
            case ABSTRACT:
                mAbstractTextView.setTextColor(getResources().getColor(R.color.green_dark));
                if(mAbstractFragment == null) {
                    mAbstractFragment = AbstractFragment.newInstance(mSingle);
                    transaction.add(R.id.fcontent, mAbstractFragment,"AbstractFragment");
                } else {
                    transaction.show(mAbstractFragment);
                }
                break;
            case CONTENT:
                mContentTextView.setTextColor(getResources().getColor(R.color.green_dark));
                if(mContentFragment == null) {
                    mContentFragment = ContentFragment.newInstance(mSingle);
                    transaction.add(R.id.fcontent, mContentFragment,"ContentFragment");
                } else {
                    transaction.show(mContentFragment);
                }
                break;
            case COMMENT:
                mCommentTextView.setTextColor(getResources().getColor(R.color.green_dark));
                if(mCommentFragment == null) {
                    mCommentFragment = CommentFragment.newInstance();
                    transaction.add(R.id.fcontent, mCommentFragment,"CommentFragment");
                } else {
                    transaction.show(mCommentFragment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void clearSelection() {
        mAbstractTextView.setTextColor(Color.BLACK);
        mContentTextView.setTextColor(Color.BLACK);
        mCommentTextView.setTextColor(Color.BLACK);
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mAbstractFragment != null) {
            transaction.hide(mAbstractFragment);
        }
        if (mContentFragment != null) {
            transaction.hide(mContentFragment);
        }
        if (mCommentFragment != null) {
            transaction.hide(mCommentFragment);
        }
    }

    @Override
    public void onClick(View v) {
        if(v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_gaiyao:
                if(mFragmentType != ThreeWayConstant.FRAGMENT_TYPE.ABSTRACT) {
                    mFragmentType = ThreeWayConstant.FRAGMENT_TYPE.ABSTRACT;
                    setTabSelection();
                }
                break;
            case R.id.tv_xiangqing:
                if(mFragmentType != ThreeWayConstant.FRAGMENT_TYPE.CONTENT) {
                    mFragmentType = ThreeWayConstant.FRAGMENT_TYPE.CONTENT;
                    setTabSelection();
                }
                break;
            case R.id.tv_pingjia:
                if(mFragmentType != ThreeWayConstant.FRAGMENT_TYPE.COMMENT) {
                    mFragmentType = ThreeWayConstant.FRAGMENT_TYPE.COMMENT;
                    setTabSelection();
                }
                break;
            case R.id.yello_layout:
                goToTelephone();
                break;
            case R.id.red_layout:
                if(TextUtils.isEmpty(ThreeWayUtil.getInstance().getLoginAccount(this))) {
                    NeedLoginDialog needLoginDialog = NeedLoginDialog.newInstance("submitYuDing");
                    needLoginDialog.show(getSupportFragmentManager(),"needLoginDialog");
                } else {
                    goSubmitInfoActivity();
                }
                break;
            case R.id.iv_favourite:
                if(TextUtils.isEmpty(ThreeWayUtil.getInstance().getLoginAccount(this))) {
                    NeedLoginDialog needLoginDialog = NeedLoginDialog.newInstance("submitFavourite");
                    needLoginDialog.show(getSupportFragmentManager(),"needLoginDialog");
                } else {
                    if(!isFavourite) {
                        goToFavourite();
                    } else {
                        goToCancelFavourite();
                    }
                }
                break;
            case R.id.btn_back:
                setResult(RESULT_OK);
                finish();
                break;
        }
    }

    private void goSubmitInfoActivity() {
        Intent intent = new Intent(SubmitActivity.this, SubmitInfoActivity.class);
        intent.putExtra("single", mSingle);
        startActivity(intent);
    }

    public void goLoginActivityForResult(String string) {
        Intent intent = new Intent(this, LoginActivity.class);
        if("submitYuDing".equals(string)) {
            startActivityForResult(intent, ThreeWayConstant.INTENT_KEY_TO_LOGIN_1);
        } else {
            startActivityForResult(intent, ThreeWayConstant.INTENT_KEY_TO_LOGIN_2);
        }
    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_pick_photo:
                    // 关联电话号码
                    Uri uri = Uri.parse("tel:18052128441");
                    Intent it = new Intent(Intent.ACTION_DIAL, uri);
                    // 启动打电话软件
                    startActivity(it);
                default:
                    break;
            }
        }
    };

    private void goToTelephone() {
        menuWindow = new SelectPicPopupWindow(this, itemsOnClick);
        // 显示窗口
        // 设置layout在PopupWindow中显示的位置
        menuWindow.showAtLocation(this.findViewById(R.id.fcontent),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ThreeWayConstant.INTENT_KEY_TO_LOGIN_2) {
            if(resultCode == RESULT_OK) {
//                mCommentFragment.getDataFromInfo();
                mCommentFragment.getLocalData();
            } else if(resultCode == -2) {
                goToFavourite();
            }
        } else if(requestCode == ThreeWayConstant.INTENT_KEY_TO_LOGIN_1) {

        }
    }

    private void goToFavourite() {
        StringRequest srPost = new StringRequest(Request.Method.POST,
                URLS.IP + "NetServlet/GoToShouCang",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String dingdan = response.toString();
                        if (dingdan.equals("true\r\n")) {
                            Toast.makeText(SubmitActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                            mIvFavourite.setImageResource(R.drawable.rating_star_green);
                            isFavourite = true;
                        } else {
                            Toast.makeText(SubmitActivity.this, "收藏失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            // 当手机发送请求时，回调用getParams方法，拼请求
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("name", mSingle.getAname());
                map.put("tel", ThreeWayUtil.getInstance().getLoginAccount(SubmitActivity.this));
                map.put("deleteFlag",mSingle.getFlagDelete());
                return map;
            }
        };
        queue.add(srPost);
    }

    private void goToCancelFavourite() {
        StringRequest srPost = new StringRequest(Request.Method.POST,
                URLS.IP + "NetServlet/DeleteShouCang",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String userlogin = response.toString();
                        if (userlogin.equals("true\r\n")) {
                            Toast.makeText(SubmitActivity.this, "取消收藏", Toast.LENGTH_SHORT).show();
                            mIvFavourite.setImageResource(R.drawable.green_favorite_normal);
                            isFavourite = false;
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            // 当手机发送请求时，回调用getParams方法，拼请求
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("SCaname", mSingle.getAname());
                map.put("SCflagdelete",mSingle.getFlagDelete());
                return map;
            }
        };
        queue.add(srPost);
    }
}
